<?php
/**
 * @brief Payease 支付插件类
 * @class Payease
 * @package App
 * @subpackage  Driver.Payment
 * @author cjli
 */
class Payease extends Payment implements Payment_Interface
{
	public function __construct()
	{
		$this->_paymentInfo = PaymentModel::get_payment_info('Payease');
	}

  public function getSettingFields()
  {
    return array(
      'merno' => '商户号',
      'md5key' => '商户密钥',
      'currency' => array(
        'name' => '支付币种',
        'type' => 'select',
        'options' => array(
          '0' => '人民币',
          '1' => '美元',
    			'2' => '欧元',
    			'3' => '英镑',
    			'4' => '日元',
    			'5' => '韩元',
        ),
        'default' => '1',
      ),
      'channels' => array(
        'name' => '支付通道类型',
        'type' => 'select',
        'options' => array(
          '0' => '易支付平台',
          '1' => '易支付会员通道',
          '2' => '易支付手机通道',
          '3' => '易支付英文通道',
        ),
        'default' => '3',
      ),
    );
  }

  public function getSubmitForm($info)
  {
    
    $country = array(
			'1' => '840', //美国
			'2' => '124', //加拿大
			'10' => '051', //亚美尼亚
			'44' => '156', //中国
			'95' => '356', //印度
			'96' => '360', //印度尼西亚
			'102' => '388', //牙买加
			'106' => '404', //肯尼亚
			'125' => '458', //马来西亚
			'149' => '840', //尼日利亚
			'181' => '702', //新加坡
			'226' => '826', //英国
		);
		
		$state = array(
				'1' => array(
					'1' => 'AL',
					'2' => 'AK',
					'3' => 'AZ',
					'4' => 'AR',
					'5' => 'CA',
					'6' => 'CO',
					'7' => 'CT',
					'8' => 'DE',
					'9' => 'FL',
					'10' => 'GA',
					'11' => 'HI',
					'12' => 'ID',
					'13' => 'IL',
					'14' => 'IN',
					'15' => 'IA',
					'16' => 'KS',
					'17' => 'KY',
					'18' => 'LA',
					'19' => 'ME',
					'20' => 'MD',
					'21' => 'MA',
					'22' => 'MI',
					'23' => 'MN',
					'24' => 'MS',
					'25' => 'MO',
					'26' => 'MT',
					'27' => 'NE',
					'28' => 'NV',
					'29' => 'NH',
					'30' => 'NJ',
					'31' => 'NM',
					'32' => 'NY',
					'33' => 'NC',
					'34' => 'ND',
					'35' => 'OH',
					'36' => 'OK',
					'37' => 'OR',
					'38' => 'PA',
					'39' => 'RI',
					'40' => 'SC',
					'41' => 'SD',
					'42' => 'TN',
					'43' => 'TX',
					'44' => 'UT',
					'45' => 'VT',
					'46' => 'VA',
					'47' => 'WA',
					'48' => 'WV',
					'49' => 'WI',
					'50' => 'WY',
					'51' => 'DC',
				),
				'2' => array(
					'52' => 'AB',
					'53' => 'BC',
					'54' => 'MB',
					'55' => 'NB',
					'56' => 'NL',
					'57' => 'NT',
					'58' => 'NS',
					'59' => 'NU',
					'60' => 'ON',
					'61' => 'PE',
					'62' => 'QC',
					'63' => 'SK',
					'64' => 'YT',
				),
			);
   
		$shippingAddress = $orderInfo['delivery_address'];
			$shippingAddress .= $orderInfo['delivery_address2'] ? '&nbsp;&nbsp;'.$orderInfo['delivery_address2'] : null;
			$shippingAddress .= $orderInfo['delivery_address3'] ? '&nbsp;&nbsp;'.$orderInfo['delivery_address3'] : null;
			
    $street =$shippingAddress;
		$city = $orderInfo['delivery_city'];
		$state = (isset($state[$orderInfo['delivery_cid']][$orderInfo['delivery_pid']]) ? $state[$orderInfo['delivery_cid']][$orderInfo['delivery_pid']] : null);
		$postcode = $orderInfo['delivery_postcode'];
		$country = (isset($country[$orderInfo['delivery_cid']]) ? $country[$orderInfo['delivery_cid']] : '826');
		$phone = ($orderInfo['delivery_phone'] ? $orderInfo['delivery_phone'] : $orderInfo['delivery_mobile']);
		$email = $orderInfo['delivery_email'];
		
    $orderNumber = $orderInfo['order_sn'];
    $orderAmount = $orderInfo['pay_amount'];
    $v_ymd       = date('Ymd',time());
    $returnUrl = url('payment/callback', array('pay' => 'Payease'));
    $v_rcvname   = trim($this->_paymentInfo['config']['merno']);

    $MD5Key     = $this->_paymentInfo['config']['md5key'];     //<--支付密钥--> 注:此处密钥必须与商家后台里的密钥一致
    $v_oid      = "$v_ymd-$v_rcvname-$orderNumber";
    $sourcedata = $this->_paymentInfo['config']['currency'].$v_ymd.$orderAmount.$v_rcvname.$v_oid.$v_rcvname.$returnUrl;
    $result     = $this->hmac_md5($MD5Key,$sourcedata);

    $channelstr = '';
    switch($this->_paymentInfo['config']['channels']){
    	case 0:
    		$channelstr = '<form id="frm" method="post" action="http://pay.beijing.com.cn/prs/user_payment.checkit" target="_blank">';
    		break;
    	case 1:
    		$channelstr = '<form id="frm" method="post" action="http://pay.beijing.com.cn/customer/gb/pay_member.jsp" target="_blank">';
    		break;
    	case 2:
    		$channelstr = '<form id="frm" method="post" action="http://pay.beijing.com.cn/customer/gb/pay_mobile.jsp" target="_blank">';
    		break;
    	default:
    		$channelstr = '<form id="frm" method="post" action="http://pay.beijing.com.cn/prs/e_user_payment.checkit" target="_blank">';
    		break;
    }

    $html = array(
      $channelstr ,
      '<input type="hidden" name = "v_mid" value= "'.$this->_paymentInfo['config']['merno'] .'">', //商户编号
      //'<input type="hidden" name="v_pmode" value="">',
      '<input type="hidden" name = "v_oid" value= "'. $v_oid .'">', //订单编号
      '<input type="hidden" name = "v_rcvname" value= "'.$v_rcvname.'">', //收货人姓名
      '<input type="hidden" name = "v_rcvaddr" value= "'.$v_rcvname.'">',
      '<input type="hidden" name = "v_rcvtel" value= "'.$v_rcvname.'">',     //收货人电话
			'<input type="hidden" name = "v_rcvpost" value= "'.$v_rcvname.'">',    //收货人邮编
			'<input type="hidden" name = "v_amount" value= "'. $orderAmount .'">',     //订单总金额
			'<input type="hidden" name = "v_ymd" value= "'.$v_ymd.'">', //订单产生日期
			'<input type="hidden" name = "v_orderstatus" value ="0">',      //配货状态
			'<input type="hidden" name = "v_ordername" value ="'.$v_rcvname.'">', //订货人姓名
			'<input type="hidden" name = "v_moneytype" value ="'. $this->_paymentInfo['config']['currency'] .'">', //币种,0为人民币,1为美元
			'<input type="hidden" name = "v_url" value="'. $returnUrl .'">',     //支付动作完成后返回到该url，支付结果以GET方式发送
			'<input type="hidden" name = "v_md5info" value="'.$result.'">',      //订单数字指纹 
      '<input type="hidden" name = "v_shipstreet" value="'.$street.'">',   //送货街道地址 
      '<input type="hidden" name = "v_shipcity" value="'.$city.'">',      //送货城市 
      '<input type="hidden" name = "v_shipstate" value="'.$state.'">',      //送货省/州
      '<input type="hidden" name = "v_shippost" value="'.$postcode.'">',      //送货邮编
      '<input type="hidden" name = "v_shipcountry" value="'.$country.'">',      //送货国家 
      '<input type="hidden" name = "v_shipphone" value="'.$phone.'">',      //送货电话
      '<input type="hidden" name = "v_shipemail" value="'.$email.'">',      //送货邮箱      
      '<input type="hidden" name = "v_billstreet" value="'.$street.'">',   //账单街道地址
      '<input type="hidden" name = "v_billcity" value="'.$city.'">',      //账单城市
      '<input type="hidden" name = "v_billstate" value="'.$state.'">',      //账单省/州
      '<input type="hidden" name = "v_billpost" value="'.$postcode.'">',      //账单邮编
      '<input type="hidden" name = "v_billcountry" value="'.$country.'">',      //账单国家 
      '<input type="hidden" name = "v_billphone" value="'.$phone.'">',      //账单电话
      '<input type="hidden" name = "v_billemail" value="'.$email.'">',      //账单邮箱     
      '<input type="submit" class="pay_button" value="' . L('_PAY_NOW_') . '">',
      '</form>',
    );
    return implode(PHP_EOL, $html);
  }

  public function callback()
  {
   //var_dump($_POST);

   $BillNo = $_REQUEST['v_oid']; //订单号
   $v_tempdate = explode('-', $BillNo);
   $Currency = $_REQUEST['v_moneytype']; //币种
   $Amount = $_REQUEST['v_amount']; //金额
   $TradeNo = $BillNo;
   $MD5info = $_REQUEST['v_md5info']; //取得的MD5校验信息



   $MD5key = $this->_paymentInfo['config']['md5key']; //MD5私钥

   $result = array(
       'verified' => false,
       'paidAmount' => $Amount,
       'paymentId' => $TradeNo,
       'orderNumber' => $v_tempdate[2],
       'updateOrderStatus' => false,
       'redirect' => '',
       'message' => '',
    );

   //接受返回数据验证开始
   //v_md5info验证
   $md5info_paramet = $BillNo . $_REQUEST['v_pstatus'] . $_REQUEST['v_pstring'] . $_REQUEST['v_pmode'];
   $md5info_tem     = $this->hmac_md5($MD5key,$md5info_paramet);

   //v_md5money验证
   $md5money_paramet = $Amount . $Currency;
   $md5money_tem     = $this->hmac_md5($MD5key,$md5money_paramet);

   if ($md5info_tem == $MD5info && $md5money_tem == $_REQUEST['v_md5money'])
   {
      $result['verified'] = true;
      $result['updateOrderStatus'] = true;
      $result['message'] = L('_PAYMENT_SUCCESS_');
   } else {
      $result['message'] = L('_PAYMENT_FAILURE_');
   }
   return $result;
  }

  private function hmac_md5($key, $data)
  {
    if (extension_loaded('mhash'))
    {
      return bin2hex(mhash(MHASH_MD5, $data, $key));
    }

    $b = 64;
    if (strlen($key) > $b)
    {
      $key = pack('H*', md5($key));
    }
    $key  = str_pad($key, $b, chr(0x00));
    $ipad = str_pad('', $b, chr(0x36));
    $opad = str_pad('', $b, chr(0x5c));

    $k_ipad = $key ^ $ipad;
    $k_opad = $key ^ $opad;

    return md5($k_opad . pack('H*', md5($k_ipad . $data)));
  }
}